package com.gxa.weixing.pc.controller;

import com.github.pagehelper.PageInfo;
import com.gxa.weixing.core.common.JsonResult;
import com.gxa.weixing.core.exception.BusinessException;
import com.gxa.weixing.core.pojo.GoodsDetail;
import com.gxa.weixing.core.pojo.GoodsListVO;
import com.gxa.weixing.pc.service.GoodsDetailService;
import com.gxa.weixing.pc.service.GoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @author lijianmin
 * @date 2022/01/06  09:55:45
 */
@RestController
@RequestMapping("/goods")
@Api(tags = "商品管理Api")
public class GoodsController {

    @Resource
    private GoodsService goodsService;

    @Resource
    private GoodsDetailService goodsDetailService;

    /**
     * 根据特定条件获取商品列表的接口
     *
     * @param map 条件
     *            name: 商品名称 模糊
     *            supplierName:供应商名称 模糊
     *            state:销售状态 (0 草稿/1 在售/2 停售)
     *            promotion:推广状态
     *            shopId: 门店编号  门店库存 - 商品选择需要此字段
     *            page: 页码
     *            size: 每页数据量
     * @return 返回信息
     */
    @PostMapping("/getGoodsList")
    @ApiOperation("根据特定条件获取商品列表的接口")
    @ApiImplicitParam(name = "map", value = "参数信息", paramType = "body")
    public Map<String, Object> getGoodsList(@RequestBody Map<String, Object> map) throws Exception {
        // 获取查询到的数据
        PageInfo<GoodsListVO> goodsList = goodsService.getGoodsList(map);
        // 给前端返回消息
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("查询成功");
        jsonResult.setData(goodsList.getList());
        jsonResult.put("count", goodsList.getTotal());
        return jsonResult.getDataMap();
    }

    /**
     * 根据特定条件获取商品列表的接口
     *
     * @param shopId  : 门店编号  如果为空或者0 则进行门店编号为空的查询
     *
     * @return 返回信息
     */
    @PostMapping("/getGoodsListByShopId")
    @ApiOperation("根据门店编号获取商品列表的接口")
    @ApiImplicitParam(name = "map", value = "参数信息", paramType = "body")
    public Map<String, Object> getGoodsListByShopId(Long shopId) {
        // 获取查询到的数据
        List<GoodsListVO> goodsListByShopId = goodsService.getGoodsListByShopId(shopId);
        // 给前端返回消息
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("查询成功");
        jsonResult.setData(goodsListByShopId);
        jsonResult.put("count", goodsListByShopId.size());
        return jsonResult.getDataMap();
    }


    /**
     * 商品列表导出接口
     *
     * @param map      name: 商品名称 模糊
     *                 supplierName:供应商名称 模糊
     *                 state:销售状态 (0 草稿/1 在售/2 停售)
     *                 promotion:推广状态
     * @param response 响应头
     * @throws BusinessException            自定义异常
     * @throws UnsupportedEncodingException 操作异常
     */
    @PostMapping("/export")
    @ApiOperation("商品列表导出接口")
    public void export(@RequestBody Map<String, Object> map, HttpServletResponse response) throws Exception {
        // 获取查询到的数据
        List<GoodsListVO> all = goodsService.getGoodsList(map).getList();

        // 工作簿对象(excel文件对象)
        HSSFWorkbook workbook = new HSSFWorkbook();

        // 创建工作表
        HSSFSheet sheet = workbook.createSheet("商品列表");
        String fileName = "商品列表.xlsx"; // 将文件名中的中文部分被URL编码后的内容进行解析, 最终还是显示为中文状态
        fileName = URLEncoder.encode(fileName, "utf-8");

        // headers表示excel表中第一行的表头 在excel表中添加表头
        String[] headers = {"商品编号", "商品名称", "销售价格(元)", "供应商", "商品规格", "总库存", "实际销售量", "剩余库存", "平台销售状态", "添加时间", "是否开启推广"};
        // 创建一个行对象, 作为表头
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            // 在行中添加单元格
            HSSFCell cell = row.createCell(i);
            //先把文字转换为标准的富文本格式
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            // 把转换后的字段名添加到表头行上
            cell.setCellValue(text);

        }
        // 添加数据行:
        int rowNum = 1;
        for (GoodsListVO item : all) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(item.getId());
            dataRow.createCell(1).setCellValue(item.getName());
            dataRow.createCell(2).setCellValue(item.getPrice().toString());
            dataRow.createCell(3).setCellValue(item.getSupplierName());
            dataRow.createCell(4).setCellValue(item.getUnit());
            dataRow.createCell(5).setCellValue(item.getInventory());
            dataRow.createCell(6).setCellValue(item.getSold());
            dataRow.createCell(7).setCellValue(item.getSurplusInventory());
            dataRow.createCell(8).setCellValue(item.getState());
            dataRow.createCell(9).setCellValue(item.getAddTime());
            dataRow.createCell(10).setCellValue(item.getPromotion());
            rowNum++;
        }
        //返回给前端下载
        response.setContentType("application/octet-stream");
        //告诉浏览器, 以附件方式打开,而不是页面上浏览
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ";" + "filename*=utf-8''" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

    /**
     * 修改商品接口
     *
     * @param map 修改信息
     * @return 返回是否成功
     */
    @PostMapping("/update")
    @ApiOperation("修改商品接口")
    @ApiImplicitParam(name = "map", value = "map", paramType = "body", dataType = "Map")
    public Map<String, Object> update(@RequestBody Map<String, Object> map) throws
            BusinessException {
        goodsService.update(map);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("修改成功");
        return jsonResult.getDataMap();
    }

    /**
     * 添加商品接口
     *
     * @param map 添加信息
     * @return 返回是否成功
     */
    @PostMapping("/add")
    @ApiOperation("添加商品接口")
    @ApiImplicitParam(name = "map", value = "map", paramType = "body", dataType = "Map")
    public Map<String, Object> add(@RequestBody Map<String, Object> map) throws BusinessException {
        goodsService.add(map);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("添加成功");
        return jsonResult.getDataMap();
    }


    /**
     * 删除商品接口
     *
     * @param id 删除商品的编号
     * @return 返回是否成功
     */
    @PostMapping("/delete")
    @ApiOperation("删除商品接口")
    @ApiImplicitParam(name = "id", value = "id", paramType = "query")
    public Map<String, Object> delete(@RequestParam("id") Long id) throws BusinessException {
        goodsService.delete(id);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("删除成功");
        return jsonResult.getDataMap();
    }


}
